<template>
	<om-page :title="title">
		<slot></slot>
		<view v-if="confirmBtn || deleteBtnFlag"  class="padding flex">
			<button v-if="deleteBtnFlag" @click="del" :style="{'width':(confirmBtn?'50%':'100%'),'margin-left':(confirmBtn?'1%':'0')}" class="bg-grey">{{ deleteBtnText}}</button>
			<button v-if="confirmBtn" class="om-history-btn" :style="{'width':(deleteBtnFlag?'50%':'100%'),'margin-left':(deleteBtnFlag?'1%':'0')}" @click="save" >{{ confirmBtnText}}</button>
		</view>
	</om-page>
</template>
<script>
	import {formValidation} from '../../../static/js/formUtil.js';
	export default {
		props: {
			title:{
				type: String,
				default() {
					return "";
				}
			},
			index: {
				type: Number,
				default() {
					return null;
				}
			},
			checkedit:{
				type: Boolean,
				default() {
					return false;
				}
			},
			confirmBtn:{
				type: Boolean,
				default() {
					return true;
				}
			},
			deleteBtn:{
				type: Boolean,
				default() {
					return true;
				}
			},
			confirmBtnText:{
				type: String,
				default() {
					return '确认';
				}
			},
			deleteBtnText:{
				type: String,
				default() {
					return '删除';
				}
			},
			customAddFunc:{
				type: Boolean,
				default() {
					return false;
				}
			},
			customDelFunc: {
				type: Boolean,
				default() {
					return false;
				}
			}
		},
		inject: ['formPage'],
		data() {
			return {
				//上传文件参数
				interval:null,
				valTimes:0,
				addTimes:0,
				deleteTimes:0,
				canClick:true
			}
		},
		computed:{
			deleteBtnFlag(){
				return this.index != null && !this.checkedit && this.deleteBtn
			}
		},
		
		methods: {
			async setData(){
				this.initParam()
				let _that = this
				var checkRes = formValidation(this.formPage.$refs.autoform.configData, this.formPage.formdata)
				if (!checkRes) {
					uni.showLoading({
						title:'请稍后……'
					})
					var fileEditors = this.formPage.$refs.autoform.getFileEditor()
					if(fileEditors.length == 1){
						var editor = fileEditors[0]
						var keepFiles = [],addFiles = [],delFiles=[];
						if(editor.tempFileList.length){
							for (var i = 0; i < editor.tempFileList.length; i++) {
								var o = editor.tempFileList[i]
								if(editor.fileUrlList.includes(o)){
									keepFiles.push(o)
								}else{
									addFiles.push(o)
								}
							}
							delFiles = editor.fileUrlList.filter(e=>!keepFiles.includes(e));
						}else{
							delFiles = editor.fileUrlList
						}
						if(delFiles){
							await _that.DelImges(delFiles, 0, editor)
						}
						if(addFiles){
							let obj = JSON.parse(JSON.stringify(_that.formPage.formdata))
							await _that.uploadImg(addFiles, 0, editor)
							Object.keys(_that.formPage.formdata).forEach((item,index)=>{
							    _that.formPage.formdata[item] = _that.formPage.formdata[item] ? _that.formPage.formdata[item] : obj[item]
							})
						}
						_that.goBack()
					}else if(fileEditors.length > 1){
						this.om.toast("有多个文件上传组件，请使用自定义上传方法")
						uni.hideLoading()
						return 
					}else{
						_that.goBack()
					}
					uni.hideLoading()
				} else {
					_that.om.toast(checkRes);
				}
			},
			initParam(){
				this.interval = null
				this.valTimes = 0
				this.addTimes = 0
				this.deleteTimes = 0
			},
			async save(){
				let _that = this
				if(!_that.canClick){
					return 
				}
				if(_that.customAddFunc){
					_that.$emit("save")
				}else{
					//确认前验证_that
					if(_that.formPage.verifySubConfirm){
						var ret =  ""
						if(typeof(_that.formPage.verifySubConfirm) == "function"){
							ret = _that.formPage.verifySubConfirm()
							if(typeof(ret) == "boolean"){
								_that.setData()
								if(!ret){
									return
								}
							} else if (typeof(ret) == "string"){
								_that.setData()
								_that.om.toast(ret)
								return
							}else if(typeof(ret) == "object"){
								ret.then(async res=>{
									ret = res
									if(typeof(ret) == "boolean"){
										if(!ret){
											return
										}
									} else if (typeof(ret) == "string"){
										_that.om.toast(ret)
										return
									}
									_that.setData()
								})
							}
						}else{
							 _that.formPage.verifySubConfirm().then( async res=>{
								ret = res
								if(typeof(ret) == "boolean"){
									if(!ret){
										return
									}
								} else if (typeof(ret) == "string"){
									_that.om.toast(ret)
									return
								}
								_that.setData()
							})
						}
					}else{
						_that.setData()
					}
				}
			},
			goBack(){
				if(this.formPage.beforeConfirm){
					this.formPage.beforeConfirm()
				}
				if(this.formPage.index != null){
					Object.assign(this.formPage.datas[this.formPage.index],this.formPage.formdata)
				}else{
					this.formPage.datas.push(this.formPage.formdata)
				}
				uni.setStorage({
				  key: this.formPage.cachename,
				  data: this.formPage.datas
				})
				uni.hideLoading()
				uni.navigateBack()
			},
			async del(){
				if(!this.canClick){
					return 
				}
				if(this.customDelFunc){
					this.$emit("delete")
				} else {
					//删除前验证
					if(this.formPage.verifySubDel){
						var ret = this.formPage.verifySubDel()
						if(typeof(ret) == "boolean"){
							if(!ret){
								return
							}
						} else if (typeof(ret) == "string"){
							this.om.toast(ret)
							return
						}
					}
					this.initParam()
					let _that = this
					var fileEditors = this.formPage.$refs.autoform.getFileEditor()
					if(fileEditors.length == 1){
						var editor = fileEditors[0]
						if(this.formPage.index != null){
							let data = this.formPage.datas.splice(this.formPage.index, 1)
							if(data){
								let o = {}
								//if(data instanceof Array){
								if(Object.prototype.toString.call(data)==='[object Array]'){
									o=data[0]
								}else{
									o=data
								}
								if(o[editor.valueField] && o[editor.valueField].length){
									await _that.DelImges(editor.fileUrlList, 0, editor)
								}
							}
						}
						_that.interval = setInterval(function(){
							_that.valTimes++
							if(_that.interval && (_that.valTimes > 20 || _that.deleteTimes == editor.fileUrlList.length)){
								clearInterval(_that.interval);
								uni.setStorage({
								  key: _that.formPage.cachename,
								  data: _that.formPage.datas
								})
								uni.navigateBack()
							}
						}, 250)
					} else if (fileEditors.length > 1){
						this.om.toast("有多个文件上传组件，请使用自定义上传方法")
						return 
					} else {
						var delData = null
						if(this.formPage.index != null) {
							delData = this.formPage.datas.splice(this.formPage.index,1)
						}
						uni.setStorage({
							 key: this.formPage.cachename,
							 data: this.formPage.datas
						})
						if(delData && this.formPage.afterdel){
							this.formPage.afterdel(delData)
						}
						uni.navigateBack()
					}
				}
			},
			async uploadImg(tempFilePaths, i, editor){
				let _that = this
				uni.showLoading({
					title:'请稍后.....'
				})
				if(tempFilePaths && tempFilePaths.length > i ){
					var filePath = tempFilePaths[i]
					_that.canClick = false
					return Promise.all([_that.om.uploadFile(_that.getUploadUrl(editor), filePath, null,{
						key: editor.fileUploadKey
					}, null, true)]).then(async d => {
						console.log(d)
						_that.addTimes++
						var json = JSON.parse(d)
						if (json.succeed) {
							if (json.value) {
								var obj = {}
								obj[_that.getFileNameField(editor)] = json.value.uploadName
								obj[_that.getFileSaveNameField(editor)] = json.value.saveName
								if(Object.prototype.toString.call( _that.formPage.$refs.autoform.formdata[editor.valueField]) !== "[object Array]"){
									 _that.formPage.$refs.autoform.formdata[editor.valueField] = new Array()
									 _that.formPage.$refs.autoform.formdata[editor.valueField].push(obj)
									_that.formPage.formdata[editor.valueField]= new Array()
									_that.formPage.formdata[editor.valueField].push(obj)
								}else{
									_that.formPage.formdata[editor.valueField].push(obj)
								}
							} else {
								_that.om.toast("上传失败，请重新上传")
							}
						} else {
							_that.om.toast(json.msg)
						}
						i++
						if(tempFilePaths.length > i){
							await _that.uploadImg(tempFilePaths, i, editor)
						}
					})
				}
			},
			async DelImges(deleteFiles, i, editor) {
				if(!i){
					i=0
				}
				let _that = this
				if(deleteFiles && deleteFiles.length > i ) {
					let index = null
					let file = _that._.find(_that.formPage.formdata[editor.valueField], function(e, ind){
						index = ind
						return e[_that.getFileSaveNameField(editor)] == deleteFiles[i]
					})
					if(file){
						return Promise.all([_that.om.request(_that.getRemoveUrl(editor), {
								fileName: file[_that.getFileSaveNameField(editor)],
								key: editor.fileUploadKey
							}, 'post')]).then(async res => {
								_that.deleteTimes++
								if (res.succeed) {
									_that.formPage.formdata[editor.valueField].splice(index, 1)
									_that.formPage.$refs.autoform.formdata[editor.valueField].splice(index, 1)
								}else{
									_that.formPage.formdata[editor.valueField].splice(index, 1)
								}
								i++
								await _that.DelImges(deleteFiles,i, editor)
							})					
					}else{
						_that.deleteTimes++
						// _that.formPage.$refs.autoform.formdata[editor.valueField].splice(index, 1)
						i++
						await _that.DelImges(deleteFiles,i, editor)
					}
				}
			},
			getFileSaveNameField(editor){
				return editor.fileSaveNameField || "fileSaveName"
			},
			getFileNameField(editor){
				return editor.fileNameField || "fileName"
			},
			getUploadUrl(editor){
				return editor.uploadUrl || "uploadFileData/uploadInterimFile"
			},
			getRemoveUrl(editor){
				return editor.removeUrl || "uploadFileData/removeInterimFile"
			}
		}
	}
</script>

<style>
</style>
